#include "BehaviacAIManager.h"

#include "Character/monster/MonsterMgr.h"

#include <sstream>
#include "CreatureCommonAI.h"
#include "generated_behaviors.h"



BehaviacAIManager::BehaviacAIManager()
{
	m_lastTick = 0;
	m_frames = 0;
}

BehaviacAIManager::~BehaviacAIManager()
{

}

void BehaviacAIManager::DeleteAI(CreatureCommonAI* pAI)
{
	if (pAI)
	{
		behaviac::Agent::Destroy(pAI);
	}
}

CreatureCommonAI* BehaviacAIManager::CreateAI(const std::string& AI, CharIDType cid)
{
	std::string monsterName;
	std::stringstream stream;
	stream << cid;
	stream >> monsterName;

	monsterName = "Creature_" + monsterName;

	CreatureCommonAI* pAI= behaviac::Agent::Create<CreatureCommonAI>(monsterName.c_str());
	if (pAI == nullptr)
	{
		return nullptr;
	}

	pAI->SetIdFlag(0);

	bool bRet = false;
	bRet = pAI->btload(AI.c_str());
	if (bRet == false)
	{
		behaviac::Agent::Destroy(pAI);
		return nullptr;
	}

	pAI->btsetcurrent(AI.c_str());

	return pAI;
}


bool BehaviacAIManager::Init(behaviac::Workspace::EFileFormat ff,
	const char* szFilePath,
	const char* szExportMetaFile)
{
#if BEHAVIAC_COMPILER_MSVC
	TCHAR szCurPath[_MAX_PATH];

	GetModuleFileName(NULL, szCurPath, _MAX_PATH);

	char* p = szCurPath;

	while (strchr(p, '\\')) {
		p = strchr(p, '\\');
		p++;
	}

	*p = '\0';

	SetCurrentDirectory(szCurPath);
#endif
//	behaviac::Config::SetSocketBlocking(false);
//	behaviac::Config::SetSocketPort(60636);

	behaviac::Workspace::GetInstance()->SetFilePath(szFilePath);
	behaviac::Workspace::GetInstance()->SetFileFormat(ff);

//	behaviac::Config::SetLogging(false);
//	behaviac::Config::SetLoggingFlush(false);
//	behaviac::Config::SetSocketing(false);

	behaviac::Agent::Register<CreatureCommonAI>();

	behaviac::Agent::SetIdMask(0xffffffff);

	behaviac::Workspace::GetInstance()->ExportMetas(szExportMetaFile);


	behaviac::Workspace::GetInstance()->SetTimeSinceStartup(0);
	behaviac::Workspace::GetInstance()->SetFrameSinceStartup(0);
	return true;
}

bool BehaviacAIManager::UnInit()
{
	behaviac::Agent::UnRegister<CreatureCommonAI>();
	behaviac::Workspace::GetInstance()->Cleanup();
	return true;
}

bool BehaviacAIManager::Update(uint64_t tick)
{
	m_frames++;

	float delta = 0;
	if (m_lastTick == 0)
	{
		m_lastTick = g_GetGlobalServerTime()->Tick();
	}

	delta = (g_GetGlobalServerTime()->Tick() - m_lastTick);

	if (delta > 100)
	{
		m_lastTick = g_GetGlobalServerTime()->Tick();
		behaviac::Workspace::GetInstance()->SetTimeSinceStartup(behaviac::Workspace::GetInstance()->GetTimeSinceStartup() + delta/1000.0f);

		//behaviac::Workspace::GetInstance()->Update();

		//g_GetMonsterMgr()->UpdateAI();
	}

	return true;
}
